package edu.jamestang.yeb.util;

import io.minio.*;
import io.minio.http.Method;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @author JamesTang
 * @date 2021/12/31 0:26
 */
@Slf4j
@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    private void createBucket(String bucketName) throws Exception{

        BucketExistsArgs existsArgs = BucketExistsArgs.builder().bucket(bucketName).build();

        if(!minioClient.bucketExists(existsArgs)){
            MakeBucketArgs makeArgs = MakeBucketArgs.builder().bucket(bucketName).build();
            minioClient.makeBucket(makeArgs);
            log.info("bucket {} 不存在， 自动创建该bucket", bucketName);
        }
    }

    public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream stream, long objectSize, String contentType) throws Exception {
        if (StringUtils.isEmpty(bucketName)) {
            throw new RuntimeException("保存的bucketName为空");
        }
        createBucket(bucketName);
        long partSize = -1;
        PutObjectArgs putArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(stream, objectSize, partSize)
                .contentType(contentType)
                .build();

        ObjectWriteResponse response = minioClient.putObject(putArgs);
        return response;
    }

    public ObjectWriteResponse uploadFile(String bucketName, String objName, MultipartFile file) throws Exception{
        return putObject(bucketName, objName, file.getInputStream(), file.getSize(), file.getContentType());
    }


}

